<template>
  <div style="height: 6vh;background-color:#fff;padding:10px 20px;">
    <span style="line-height:60px;font-size:20px;">轮播图管理</span>
    <el-button @click="openDialog('add')" type="danger" style="float:right;margin-top:13px;">新建轮播图</el-button>
  </div>
  <!-- 新增轮播图弹窗 -->
  <el-dialog :title="dialogTitle" v-model="dialogVisible"
             style="width:1000px;padding:40px;" :before-close="handleClose">
    <el-form label-width="80px" label-position="top">
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="轮播图名称">
            <el-input placeholder="请输入内容" v-model="saveCarouselForm.carouselName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="轮播图">
            <el-upload
                v-model:file-list="fileList"
                v-model:action="actionUrl"
                name="file"
                limit="1"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
            >
              <el-icon>
                <Plus/>
              </el-icon>
            </el-upload>
            <el-dialog v-model="previewDialogVisible">
              <img w-full :src="dialogImageUrl"/>
            </el-dialog>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="排序">
            <el-input placeholder="请输入内容" v-model="saveCarouselForm.sort"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否轮播">
            <el-select placeholder="请选择" v-model="saveCarouselForm.isShow">
              <el-option label="是" value="1"></el-option>
              <el-option label="否" value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!--      <h4>显示后端返回的图片路径是: <span>{{fileList}}</span></h4>-->
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="saveCarousel">确定</el-button>
    </template>
  </el-dialog>
  <!-- 轮播图列表 -->
  <el-card style="margin:20px;">
    <el-table :data="carouselArr">
      <el-table-column type="index" label="ID" width="80" align="center"/>
      <el-table-column prop="carouselName" label="轮播图名称" align="center"/>
      <el-table-column label="图片" align="center">
        <template #default="scope">
          <!-- 使用 el-image 组件展示图片，src 绑定图片地址 -->
          <el-image :src="BASE_URL+scope.row.image" style="width: 200px; height: 200px"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" align="center"/>
      <el-table-column prop="isShow" label="是否展示" align="center">
        <template #default="scope">
          <span>{{ scope.row.isShow =='1'?'是':'否'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="editCarousel(scope.row.id)">编辑</el-button>
          <el-button link type="primary" size="small" @click="deleteCarousel(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>
<script setup>
import {onMounted, ref} from "vue";
import qs from "qs";
import axios from "axios";
import {ElMessage} from "element-plus";

// 控制新增弹窗是否显示
const previewDialogVisible = ref(false);

// 图片上传相关代码开始/
const fileList = ref([]);
const dialogImageUrl = ref('');
const dialogVisible = ref(false);

// 定义变量用来保存图片上传给哪个后端接口地址
const actionUrl = ref(BASE_URL+'/v1/file/upload');

// 移除图片
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
  // 1.得到要删除的图片路径 uploadFile就是我们要删除的那个图片文件对象
  let imgUrl = uploadFile.response.data;
  // 2.给后端发请求,删除图片
  axios.post(BASE_URL+'/v1/file/remove?imgUrl='+imgUrl)
      .then((response) => {
        if (response.data.code === 2000) {
          ElMessage.success('删除成功!');
        }
      })
}

// 图片上传后预览
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url;
  previewDialogVisible.value = true;
  console.log(uploadFile);
}

// 定义变量控制dialog的标题
const dialogTitle = ref('新增轮播图');

// 新增/编辑表单数据
const saveCarouselForm = ref({carouselName: '', image: '', sort: '', isShow: ''});

// 区分当前是新增还是编辑状态
const dialogMode = ref('add'); // 'add' 或 'edit'

const searchCarousel = ref('');
const carouselArr = ref([]);

const loadCarousel = () => {
  let data = qs.stringify(searchCarousel.value);
  console.log("数据", data);
  axios.get(BASE_URL+'/v1/carousel/select?'+data).then((response) => {
    if (response.data.code === 2000) {
      carouselArr.value = response.data.data;
      console.log(response.data.data);
      console.log(carouselArr.value);
    } else {
      ElMessage.error(response.data.message);
    }
  })
}

// 页面加载完毕，立即首次加载车辆列表数据
onMounted(() => {
  loadCarousel();
})

// 打开弹窗的方法，接收mode参数区分是新增还是编辑
const openDialog = (mode) => {
  dialogMode.value = mode;
  dialogVisible.value = true;

  if (mode === 'add') {
    dialogTitle.value = '新增轮播图';
    // 清空表单数据
    saveCarouselForm.value = {carouselName: '', image: '', sort: '', isShow: ''};
    fileList.value = [];
  } else {
    dialogTitle.value = '编辑轮播图';
  }
}

// 新增轮播图
const saveCarousel = () => {
  if (fileList.value.length === 0) {
    ElMessage.error('请上传图片!');
    return;
  }

  saveCarouselForm.value.image = fileList.value[0].response.data;
  console.log(saveCarouselForm.value);

  let url = dialogMode.value === 'add'
      ? BASE_URL + '/v1/carousel/save'
      : BASE_URL + '/v1/carousel/save';

  // let method = dialogMode.value === 'add' ? 'post' : 'put';

  axios.post(url, qs.stringify(saveCarouselForm.value)).then((response) => {
    if (response.data.code === 2000) {
      ElMessage.success("保存成功!");
      dialogVisible.value = false;
      loadCarousel();
    } else if (response.data.code === 3001) {
      ElMessage.error(response.data.data);
    } else {
      ElMessage.error(response.data.message);
    }
  })
}

// 处理保存轮播图弹窗关闭的方法
const handleClose = () => {
  if (dialogMode.value === 'add') {
    // 新增模式下执行完整的关闭逻辑
    if(confirm('您确认要关闭本弹窗吗?')){
      saveCarouselForm.value = {}; // 清空表单

      if (fileList.value.length > 0) {
        handleRemove(fileList.value[0], fileList.value);
      }

      fileList.value = [];
      dialogVisible.value = false;
    }
  } else {
    if (confirm('您确定要关闭本弹窗吗?')){
      // 编辑模式下只关闭弹窗
      dialogVisible.value = false;
    }

  }
}

// 编辑轮播图
const editCarousel = (id) => {
  openDialog('edit'); // 设置为编辑模式

  axios.get(BASE_URL+'/v1/carousel/select?id='+id).then((response) => {
    if (response.data.code === 2000) {
      saveCarouselForm.value = response.data.data[0];

      if (saveCarouselForm.value.image) {
        const fileObj = {
          url: BASE_URL + saveCarouselForm.value.image,
          response: {data: saveCarouselForm.value.image}
        };

        console.log(fileObj.url);
        fileList.value = [fileObj];
      }
    } else {
      ElMessage.error(response.data.message);
    }
  })
}

// 删除轮播图
const deleteCarousel = (carouselId) => {
  if (confirm("您确定要删除该轮播图吗?")) {
    axios.post(BASE_URL+'/v1/carousel/delete/'+carouselId).then((response) => {
      if (response.data.code === 2000) {
        ElMessage.success('删除成功!');
        loadCarousel();
      } else {
        ElMessage.error(response.data.message);
      }
    })
  }
}
</script>